﻿using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Text;

namespace VIP.Infrastructure.Serializer
{
    public class Serializer : ISerializer
    {
        public Serializer()
        {
            this.Settgins = new JsonSerializerSettings
            {

                TypeNameHandling = TypeNameHandling.Auto,
                PreserveReferencesHandling = PreserveReferencesHandling.Objects,
                ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
                DateFormatString = "yyyy-MM-dd HH:mm:ss",
                ContractResolver = new CamelCasePropertyNamesContractResolver()//设置默认采用骆驼命名规则 如userName
            };
        }


        private readonly JsonSerializerSettings Settgins;

        public T DeSerialize<T>(string source)
        {
            try
            {
                return JsonConvert.DeserializeObject<T>(source, this.Settgins);
            }
            catch (Exception)
            {
                throw;
            }
        }

        public object DeSerialize(string source, Type type)
        {
            return JsonConvert.DeserializeObject(source, type, this.Settgins);
        }

        public string Serialize(object obj)
        {
            return JsonConvert.SerializeObject(obj, this.Settgins);
        }
    }
}
